package com.atguigu.exam.service.impl;

import com.atguigu.exam.properties.MinioProperties;
import com.atguigu.exam.service.FileUploadService;
import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Service
@Slf4j

public class FileUploadServiceImpl implements FileUploadService {
    @Autowired
    private MinioProperties minioProperties;
    @Override
    public String uploadFile(MultipartFile file) {
        try {
            //构造MinIO Client （登录）
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(minioProperties.getEndpoint())
                            .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                            .build();
            //创建hello-minio桶
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {
                System.out.println("Bucket" + minioProperties.getBucketName() + "+already exists.");
            }
            String uploadFileName = file.getOriginalFilename();
            String suffix = uploadFileName.substring(uploadFileName.lastIndexOf("."));
            String prefix = UUID.randomUUID().toString().replaceAll("-", "");
            String format = DateFormatUtils.format(new Date(), "yyyy/MM/dd");
            String newFileName = format + "/" + prefix + suffix;
            InputStream is = file.getInputStream();
            long size = file.getSize();
            //上传图片
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .object(newFileName)
                    .stream(is, size, -1)
                    .build());
            return minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + newFileName;
        } catch (Exception e) {
            System.out.println("Error occurred: " + e);
        }
        return null;
    }
}
